﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.Materials.Dtos;
using KDS.Mes.Authorization;
using KDS.Mes.Dto;
using Abp.UI;

namespace KDS.Mes.Mes.Materials
{
    /// <summary>
    /// 材质信息服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Bom_Materials)]
    public class MaterialAppService : MesAppServiceBase, IMaterialAppService
    {
        private readonly IRepository<Material, int> _materialRepository;
        private readonly IMaterialListExcelExporter _materialListExcelExporter;


        private readonly MaterialManage _materialManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public MaterialAppService(IRepository<Material, int> materialRepository,
MaterialManage materialManage
      , IMaterialListExcelExporter materialListExcelExporter
  )
        {
            _materialRepository = materialRepository;
            _materialManage = materialManage;
            _materialListExcelExporter = materialListExcelExporter;
        }

        #region 材质信息管理

        public PagedResultDto<MaterialListDto> GetPagedMaterials(GetMaterialInput input)
        {
            //初步过滤
            var query = _materialRepository.GetAll();
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.CreationTime);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<MaterialListDto>(tasksCount, taskList.MapTo<List<MaterialListDto>>());
        }

        /// <summary>
        /// 根据查询条件获取材质信息分页列表
        /// </summary>
        public async Task<PagedResultDto<MaterialListDto>> GetPagedMaterialsAsync(GetMaterialInput input)
        {

            var query = _materialRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var materialCount = await query.CountAsync();

            var materials = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var materialListDtos = materials.MapTo<List<MaterialListDto>>();
            return new PagedResultDto<MaterialListDto>(
            materialCount,
            materialListDtos
            );
        }

        /// <summary>
        /// 通过Id获取材质信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetMaterialForEditOutput> GetMaterialForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetMaterialForEditOutput();

            MaterialEditDto materialEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _materialRepository.GetAsync(input.Id.Value);
                materialEditDto = entity.MapTo<MaterialEditDto>();
            }
            else
            {
                materialEditDto = new MaterialEditDto();
            }

            output.Material = materialEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取材质信息ListDto信息
        /// </summary>
        public async Task<MaterialListDto> GetMaterialByIdAsync(EntityDto<int> input)
        {
            var entity = await _materialRepository.GetAsync(input.Id);

            return entity.MapTo<MaterialListDto>();
        }







        /// <summary>
        /// 新增或更改材质信息
        /// </summary>
        public async Task CreateOrUpdateMaterialAsync(CreateOrUpdateMaterialInput input)
        {
            if (input.MaterialEditDto.Id.HasValue)
            {
                await UpdateMaterialAsync(input.MaterialEditDto);
            }
            else
            {
                await CreateMaterialAsync(input.MaterialEditDto);
            }
        }

        /// <summary>
        /// 新增材质信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Materials_Create)]
        public virtual async Task<MaterialEditDto> CreateMaterialAsync(MaterialEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            await CheckMaterialIfAlreadyExists(input);
            var entity = input.MapTo<Material>();

            entity = await _materialRepository.InsertAsync(entity);
            return entity.MapTo<MaterialEditDto>();
        }

        /// <summary>
        /// 编辑材质信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Materials_Edit)]
        public virtual async Task UpdateMaterialAsync(MaterialEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            await CheckMaterialIfAlreadyExists(input);
            var entity = await _materialRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _materialRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除材质信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Materials_Delete)]
        public async Task DeleteMaterialAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _materialRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除材质信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Materials_Delete)]
        public async Task BatchDeleteMaterialAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _materialRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        private async Task CheckMaterialIfAlreadyExists(MaterialEditDto input)
        {
            var existingMaterial = await _materialRepository.GetAll()
                .FirstOrDefaultAsync(l => l.MaterialName == input.MaterialName || l.MaterialCode == input.MaterialCode);
            if (existingMaterial == null)
            {
                return;
            }
            if (input.Id != null && existingMaterial.Id == input.Id)
            {
                return;
            }
            throw new UserFriendlyException(L("ThisMaterialAlreadyExists"));
        }

        #endregion


        #region 材质信息的Excel导出功能


        public async Task<FileDto> GetMaterialToExcel()
        {
            var entities = await _materialRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<MaterialListDto>>();

            var fileDto = _materialListExcelExporter.ExportMaterialToFile(dtos);



            return fileDto;
        }


        #endregion










    }
}
